package playitas

import twitter4j.Twitter
import twitter4j.TwitterFactory
import twitter4j.http.RequestToken
import twitter4j.http.AccessToken
import twitter4j.TwitterException
import twitter4j.User

class HomeController
{

  def consumerKey =   "59nGO9G3H9XTi3Fs5RrPDQ"
  def consumerSecret = "NgadQMIY2TqBZ6yK1p88OkUI2MNXZGmXix91rchMfw"

  static Twitter twitter = null;
  
    def index = { }

   def loginTwitter = {
      def twitter = createTwitter()

     RequestToken requestToken = twitter.getOAuthRequestToken("http://localhost:8080/twitter/home/callback")
     session.requestToken = requestToken

     def twitterUrl = requestToken.getAuthorizationURL().replaceAll("authorize","authenticate")

     redirect url : twitterUrl

   }

    private createTwitter() {
      if ( this.twitter == null ) {
        this.twitter = new TwitterFactory().getInstance()
        this.twitter.setOAuthConsumer (consumerKey, consumerSecret)
      }
      return this.twitter
    }

    def callback = {
      RequestToken requestToken = session.requestToken
      if (!requestToken) return redirect (action:index)

      session.requestToken = null

      def twitter = createTwitter()

      AccessToken accessToken
      try {
        accessToken = twitter.getOAuthAccessToken(requestToken, params.oauth_verifier)
      } catch (TwitterException e)   {
        return redirect (action:index)
      }

      User user = twitter.verifyCredentials()

      Usuario miUsuario = Usuario.findByTwitterId(user.id)
      if ( miUsuario == null ) {
        miUsuario = new Usuario();
        miUsuario.twitterId = user.id
      }
        miUsuario.setName (user.getName());
        miUsuario.url = user.profileImageURL;
        miUsuario.screenName = user.screenName

        miUsuario.token = accessToken.token
        miUsuario.tokenSecret = accessToken.tokenSecret

        miUsuario.save()

        session.usuario = miUsuario

      redirect action: index
    }

  def logOut = {
    session.invalidate()
    redirect action: index
  }
}
